
package com.lanou.myim.ui.activity;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.lanou.myim.R;
import com.lanou.myim.adapter.MyGrideviewAdapter;
import com.lanou.myim.adapter.PrivateChatActivityAdapter;
import com.lanou.myim.entity.MsgEty;
import com.lanou.myim.entity.MsgFromEty;
import com.lanou.myim.presenter.PrivateChatPresenter;
import com.lanou.myim.presenter.PrivateChatPresenterInterface;
import com.lanou.myim.tools.SoundMeter;

import java.io.File;
import java.io.IOException;
import java.util.IllegalFormatCodePointException;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by dllo on 16/3/22.
 */
public class PrivateChatActivity extends BaseActivity implements View.OnClickListener, PrivateChatActivityInterface {
    private Button voiceBtn;
    private Button keyBordBtn;
    private View pressToSpeak;
    private EditText etsendmessage;
    private View edittextLayout;
    private ImageView faceNormalIv;
    private ImageView faceCheckIv;
    private Button moreBtn;
    private Button sendBtn;
    private View emoticonLayout;
    private View sendAddLayout;
    private boolean first = true;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private PrivateChatActivityAdapter adapter;
    private TextView chatFriendNameTv;
    private ImageView clearMsgsIv;
    private ImageView backPressIv;
    private ImageView groupSetIIv;
    private PrivateChatPresenterInterface privateChatPresenter;
    private String chatFriendName;
    private String layoutName;
    private boolean isGroup;
    private View sendImageLayout;
    private final int IMAGE_CODE = 0;
    private final int PHOTOGRAPH_CODE = 1;
    private View sendPhotograph;
    private String imageFilePath;
    private boolean voiceMode = false;
    private SoundMeter soundMeter;
    private static final int POLL_INTERVAL = 300;
    private Handler mHandler = new Handler();
    private RelativeLayout voiceAnimationLayout;
    private ImageView voiceIv;
    private TextView voiceTv;
    private boolean flag = false;
    private String voiceName;
    private long startTime;
    private float down_y;
    private boolean cancleRecord = false;

    private GridView emotionGv;
    private MyGrideviewAdapter grideviewAdapter;
    private int[] imageIds = new int[]{R.drawable.ee_1,R.drawable.ee_2,R.drawable.ee_3
            ,R.drawable.ee_4,R.drawable.ee_5,R.drawable.ee_6,R.drawable.ee_7,R.drawable.ee_8,
            R.drawable.ee_9,R.drawable.ee_10,R.drawable.ee_11,R.drawable.ee_12,R.drawable.ee_13,
            R.drawable.ee_14,R.drawable.ee_14,R.drawable.ee_15,R.drawable.ee_16,R.drawable.ee_17,
            R.drawable.ee_17,R.drawable.ee_18,R.drawable.ee_19,R.drawable.ee_20,};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_private_chat_strong);
        EventBus.getDefault().register(this);
        MsgFromEty msgFromEty = (MsgFromEty) getIntent().getSerializableExtra("ID");
        if (msgFromEty.getMsgFrom().equals("FRIEND")) {
            chatFriendName = msgFromEty.getFriendName();
            layoutName = chatFriendName;
            isGroup = false;
        } else if (msgFromEty.getMsgFrom().equals("GROUP")) {
            chatFriendName = msgFromEty.getGroupId();
            layoutName = msgFromEty.getGroupName();
            isGroup = true;
        }
        emotionGv = (GridView) findViewById(R.id.gv_emotion);
        grideviewAdapter = new MyGrideviewAdapter(this,imageIds);
        emotionGv.setAdapter(grideviewAdapter);
        chatFriendNameTv = (TextView) findViewById(R.id.chat_friend_name);
        chatFriendNameTv.setText(layoutName);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_recycleview);
        recyclerView = (RecyclerView) findViewById(R.id.private_chat_recycleView);
        clearMsgsIv = (ImageView) findViewById(R.id.iv_clear_msgs);
        clearMsgsIv.setOnClickListener(this);
        backPressIv = (ImageView) findViewById(R.id.iv_back_press);
        groupSetIIv = (ImageView) findViewById(R.id.iv_group_set);
        if (isGroup) {
            groupSetIIv.setVisibility(View.VISIBLE);
            clearMsgsIv.setVisibility(View.GONE);
        } else {
            groupSetIIv.setVisibility(View.GONE);
            clearMsgsIv.setVisibility(View.VISIBLE);
        }
        backPressIv.setOnClickListener(this);
        groupSetIIv.setOnClickListener(this);
        voiceBtn = (Button) findViewById(R.id.btn_set_mode_voice);
        keyBordBtn = (Button) findViewById(R.id.btn_set_mode_keyboard);
        pressToSpeak = findViewById(R.id.btn_press_to_speak);
        edittextLayout = findViewById(R.id.edittext_layout);
        faceNormalIv = (ImageView) findViewById(R.id.iv_face_normal);
        faceCheckIv = (ImageView) findViewById(R.id.iv_face_checked);
        moreBtn = (Button) findViewById(R.id.btn_more);
        sendBtn = (Button) findViewById(R.id.btn_send);
        emoticonLayout = findViewById(R.id.layout_emoticon);
        sendAddLayout = findViewById(R.id.send_add);
        etsendmessage = (EditText) findViewById(R.id.et_sendmessage);
        sendImageLayout = findViewById(R.id.layout_send_image);
        sendPhotograph = findViewById(R.id.layout_photograph);
        sendImageLayout.setOnClickListener(this);
        sendPhotograph.setOnClickListener(this);
        voiceBtn.setOnClickListener(this);
        keyBordBtn.setOnClickListener(this);
        faceNormalIv.setOnClickListener(this);
        faceCheckIv.setOnClickListener(this);
        moreBtn.setOnClickListener(this);
        sendBtn.setOnClickListener(this);
        voiceBtn.setVisibility(View.VISIBLE);
        edittextLayout.setVisibility(View.VISIBLE);
        faceNormalIv.setVisibility(View.VISIBLE);
        moreBtn.setVisibility(View.VISIBLE);
        keyBordBtn.setVisibility(View.GONE);
        pressToSpeak.setVisibility(View.GONE);
        faceCheckIv.setVisibility(View.GONE);
        sendBtn.setVisibility(View.GONE);
        emoticonLayout.setVisibility(View.GONE);
        sendAddLayout.setVisibility(View.GONE);
        etsendmessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    sendBtn.setVisibility(View.GONE);
                    moreBtn.setVisibility(View.VISIBLE);
                } else {
                    moreBtn.setVisibility(View.GONE);
                    sendBtn.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        privateChatPresenter = new PrivateChatPresenter(this);
        privateChatPresenter.init(chatFriendName);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                privateChatPresenter.getMoreMsgs(chatFriendName);
                swipeRefreshLayout.setRefreshing(false);
            }
        });


        pressToSpeak.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });


        soundMeter = new SoundMeter();
        voiceAnimationLayout = (RelativeLayout) findViewById(R.id.layout_voice_animation);
        voiceIv = (ImageView) findViewById(R.id.mic_image);
        voiceTv = (TextView) findViewById(R.id.recording_hint);
        voiceAnimationLayout.setVisibility(View.GONE);


        emotionGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Html.ImageGetter imageGetter = new Html.ImageGetter() {
                    @Override
                    public Drawable getDrawable(String source) {
                        int id = Integer.parseInt(source);
                        Drawable d = getResources().getDrawable(id);
                        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                        return d;
                    }
                };

                CharSequence cs = Html.fromHtml("<img src='" + imageIds[position]+ "'/>",imageGetter, null);
                etsendmessage.getText().append(cs);
                String con =FilterHtml(Html.toHtml(etsendmessage.getText()));
            }
        });


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back_press:
                onBackPressed();
                break;
            case R.id.iv_group_set:
                Intent intent = new Intent(this,SetGroupActivity.class);
                intent.putExtra("groupId",chatFriendName);
                startActivity(intent);
                break;
            case R.id.btn_set_mode_voice:
                first = true;
                voiceBtn.setVisibility(View.GONE);
                edittextLayout.setVisibility(View.GONE);
                sendBtn.setVisibility(View.GONE);
                emoticonLayout.setVisibility(View.GONE);
                sendAddLayout.setVisibility(View.GONE);
                keyBordBtn.setVisibility(View.VISIBLE);
                pressToSpeak.setVisibility(View.VISIBLE);
                moreBtn.setVisibility(View.VISIBLE);
                voiceMode = true;
                break;
            case R.id.btn_set_mode_keyboard:
                first = true;
                emoticonLayout.setVisibility(View.GONE);
                sendAddLayout.setVisibility(View.GONE);
                keyBordBtn.setVisibility(View.GONE);
                pressToSpeak.setVisibility(View.GONE);
                sendBtn.setVisibility(View.GONE);
                faceCheckIv.setVisibility(View.GONE);
                voiceBtn.setVisibility(View.VISIBLE);
                edittextLayout.setVisibility(View.VISIBLE);
                faceNormalIv.setVisibility(View.VISIBLE);
                moreBtn.setVisibility(View.VISIBLE);
                voiceMode = false;
                break;
            case R.id.iv_face_normal:
                first = true;
                voiceBtn.setVisibility(View.VISIBLE);
                edittextLayout.setVisibility(View.VISIBLE);
                faceCheckIv.setVisibility(View.VISIBLE);
                moreBtn.setVisibility(View.VISIBLE);
                emoticonLayout.setVisibility(View.VISIBLE);
                keyBordBtn.setVisibility(View.GONE);
                pressToSpeak.setVisibility(View.GONE);
                faceNormalIv.setVisibility(View.GONE);
                sendBtn.setVisibility(View.GONE);
                sendAddLayout.setVisibility(View.GONE);
                voiceMode = false;
                break;
            case R.id.iv_face_checked:
                first = true;
                emoticonLayout.setVisibility(View.GONE);
                sendAddLayout.setVisibility(View.GONE);
                keyBordBtn.setVisibility(View.GONE);
                pressToSpeak.setVisibility(View.GONE);
                sendBtn.setVisibility(View.GONE);
                faceCheckIv.setVisibility(View.GONE);
                voiceBtn.setVisibility(View.VISIBLE);
                edittextLayout.setVisibility(View.VISIBLE);
                faceNormalIv.setVisibility(View.VISIBLE);
                moreBtn.setVisibility(View.VISIBLE);
                voiceMode = false;
                break;
            case R.id.btn_more:
                if (first) {
                    emoticonLayout.setVisibility(View.GONE);
                    keyBordBtn.setVisibility(View.GONE);
                    pressToSpeak.setVisibility(View.GONE);
                    sendBtn.setVisibility(View.GONE);
                    faceCheckIv.setVisibility(View.GONE);
                    voiceBtn.setVisibility(View.VISIBLE);
                    edittextLayout.setVisibility(View.VISIBLE);
                    faceNormalIv.setVisibility(View.VISIBLE);
                    moreBtn.setVisibility(View.VISIBLE);
                    sendAddLayout.setVisibility(View.VISIBLE);
                    first = false;
                    voiceMode = false;
                } else {
                    emoticonLayout.setVisibility(View.GONE);
                    keyBordBtn.setVisibility(View.GONE);
                    pressToSpeak.setVisibility(View.GONE);
                    sendBtn.setVisibility(View.GONE);
                    faceCheckIv.setVisibility(View.GONE);
                    voiceBtn.setVisibility(View.VISIBLE);
                    edittextLayout.setVisibility(View.VISIBLE);
                    faceNormalIv.setVisibility(View.VISIBLE);
                    moreBtn.setVisibility(View.VISIBLE);
                    sendAddLayout.setVisibility(View.GONE);
                    first = true;
                    voiceMode = false;
                }


                break;
            case R.id.iv_clear_msgs:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("注意");
                builder.setMessage("确定删除与该联系人的所有聊天记录吗?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        privateChatPresenter.clearMsgs(chatFriendName);
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
                break;
            case R.id.btn_send:
                String content = FilterHtml(Html.toHtml(etsendmessage.getText()));
                privateChatPresenter.sendText(chatFriendName, content, isGroup);
                etsendmessage.setText("");
                break;
            case R.id.layout_send_image:
                Intent intent1 = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, IMAGE_CODE);
                break;
            case R.id.layout_photograph:
                imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/Android/data/com.lanou.myim/easemob-demo#chatdemoui/"
                        + EMChatManager.getInstance().getCurrentUser() + "/image/"
                        + EMChatManager.getInstance().getCurrentUser() + System.currentTimeMillis() + ".jpg";
                File temp = new File(imageFilePath);
                Uri imageFileUri = Uri.fromFile(temp);//获取文件的Uri
                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//跳转到相机Activity
                it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);//告诉相机拍摄完毕输出图片到指定的Uri
                startActivityForResult(it, PHOTOGRAPH_CODE);
                break;

        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        privateChatPresenter.clearUnreadMsgs(chatFriendName);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMainEvent(EMMessage emMessage) {
        //是群聊对话,对比群ID
        if (isGroup&&chatFriendName.equals(emMessage.getTo())){
            privateChatPresenter.receiveMsgs(chatFriendName);
            //是私聊对话,对比联系人姓名
        }else if (!isGroup&&chatFriendName.equals(emMessage.getFrom())){
            privateChatPresenter.receiveMsgs(chatFriendName);
        }
    }

    @Override
    public void refreshList(List<EMMessage> messages) {
        adapter.refreshData(messages);
        int i = EMChatManager.getInstance().getConversation(chatFriendName).getAllMsgCount();
        recyclerView.smoothScrollToPosition(i);
        Toast.makeText(PrivateChatActivity.this, "刷新消息", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void init(List<EMMessage> messages) {
        adapter = new PrivateChatActivityAdapter(this, messages);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        int i = EMChatManager.getInstance().getConversation(chatFriendName).getAllMsgCount();
        recyclerView.smoothScrollToPosition(i);
    }

    @Override
    public void refreshMore(List<EMMessage> messages) {
        adapter.refreshData(messages);
        recyclerView.smoothScrollToPosition(0);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {        //此处的 RESULT_OK 是系统自定义得一个常量
            return;
        }
        Bitmap bm = null;
        //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
        ContentResolver resolver = getContentResolver();
        //此处的用于判断接收的Activity是不是你想要的那个
        if (requestCode == IMAGE_CODE) {
            try {
                Uri originalUri = data.getData();        //获得图片的uri
                bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);        //显得到bitmap图片
                //这里开始的第二部分，获取图片的路径：
                String[] proj = {MediaStore.Images.Media.DATA};
                //好像是android多媒体数据库的封装接口，具体的看Android文档
                Cursor cursor = managedQuery(originalUri, proj, null, null, null);
                //按我个人理解 这个是获得用户选择的图片的索引值
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                //将光标移至开头 ，这个很重要，不小心很容易引起越界
                cursor.moveToFirst();
                //最后根据索引值获取图片路径
                String path = cursor.getString(column_index);
                Toast.makeText(PrivateChatActivity.this, path, Toast.LENGTH_SHORT).show();
                privateChatPresenter.sendPicture(chatFriendName, path, isGroup);
            } catch (IOException e) {

            }

        } else if (resultCode != RESULT_CANCELED&&requestCode == PHOTOGRAPH_CODE) {
            privateChatPresenter.sendPicture(chatFriendName, imageFilePath, isGroup);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!Environment.getExternalStorageDirectory().exists()) {
            Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
            return false;
        }
        if (voiceMode) {
            int[] location = new int[2];
            pressToSpeak.getLocationInWindow(location);
            int press_x = location[0];
            int press_y = location[1];
            if (event.getAction() == MotionEvent.ACTION_DOWN
                    && event.getX() > press_x && event.getY() > press_y) {
                startTime = System.currentTimeMillis();
                voiceName = EMChatManager.getInstance().getCurrentUser() + startTime + ".amr";
                voiceAnimationLayout.setVisibility(View.VISIBLE);
                flag = true;
                down_y = (int) event.getRawY();
                start(voiceName);
            } else if (event.getAction() == MotionEvent.ACTION_MOVE && flag) {
                float move_y = event.getRawY();
                int distance = (int) (down_y - move_y);
                if (distance > 50) {
                    voiceTv.setText("松手取消发送");
                    cancleRecord = true;
                } else {
                    voiceTv.setText("上滑取消发送");
                    cancleRecord = false;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP && flag) {
                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/Android/data/com.lanou.myim/easemob-demo#chatdemoui/"
                        + EMChatManager.getInstance().getCurrentUser() + "/voice/"
                        + voiceName;
                if (cancleRecord) {
                    flag = false;
                    stop();
                    voiceAnimationLayout.setVisibility(View.GONE);
                    File file = new File(filePath);
                    if (file.exists()) {
                        file.delete();
                    }
                } else {
                    flag = false;
                    stop();
                    voiceAnimationLayout.setVisibility(View.GONE);
                    long stopTime = System.currentTimeMillis();
                    int time = (int) (stopTime - startTime) / 1000;
                    if (time < 1) {
                        Toast.makeText(PrivateChatActivity.this, "录音时间太短", Toast.LENGTH_SHORT).show();
                    }
                    //消息录制成功,发送消息
                    privateChatPresenter.sendVoice(chatFriendName, filePath, time, isGroup);
                }
            }
        }
        return super.onTouchEvent(event);
    }

    private Runnable mSleepTask = new Runnable() {
        public void run() {
            stop();
        }
    };
    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = soundMeter.getAmplitude();
            updateDisplay(amp);
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);

        }
    };

    private void start(String name) {
        soundMeter.start(name);
        mHandler.postDelayed(mPollTask, POLL_INTERVAL);
    }

    private void stop() {
        mHandler.removeCallbacks(mSleepTask);
        mHandler.removeCallbacks(mPollTask);
        soundMeter.stop();
    }

    private void updateDisplay(double signalEMA) {

        switch ((int) signalEMA) {
            case 0:
                voiceIv.setImageResource(R.drawable.ease_record_animate_01);
                break;
            case 1:
                voiceIv.setImageResource(R.drawable.ease_record_animate_02);
                break;
            case 2:
                voiceIv.setImageResource(R.drawable.ease_record_animate_03);
                break;
            case 3:
                voiceIv.setImageResource(R.drawable.ease_record_animate_04);
                break;
            case 4:
                voiceIv.setImageResource(R.drawable.ease_record_animate_05);
                break;
            case 5:
                voiceIv.setImageResource(R.drawable.ease_record_animate_06);
                break;
            case 6:
                voiceIv.setImageResource(R.drawable.ease_record_animate_07);
                break;
            case 7:
                voiceIv.setImageResource(R.drawable.ease_record_animate_08);
                break;
            case 8:
                voiceIv.setImageResource(R.drawable.ease_record_animate_08);
                break;
            case 9:
                voiceIv.setImageResource(R.drawable.ease_record_animate_09);
                break;
            case 10:
                voiceIv.setImageResource(R.drawable.ease_record_animate_10);
                break;
            case 11:
                voiceIv.setImageResource(R.drawable.ease_record_animate_11);
                break;
            default:
                voiceIv.setImageResource(R.drawable.ease_record_animate_12);
                break;
        }
    }

    public static String FilterHtml(String str){
        str = str .replaceAll("<(?!br|img)[^>]+>", "").trim();
//        return UnicodeToGBK2(str);
        return str;
    }
    public static String UnicodeToGBK2(String s){
        String[] k = s.split(";") ;
        String rs = "" ;
        for(int i=0;i<k.length;i++) {
            int strIndex = k[i].indexOf("&#");
            String newstr = k[i];
            if(strIndex>-1) {
                String kstr = "";
                if(strIndex>0) {
                    kstr = newstr.substring(0,strIndex);
                    rs+=kstr;
                    newstr = newstr.substring(strIndex);
                }
                int m = Integer.parseInt(newstr.replace("&#",""));
                char c = (char)m ;
                rs+= c ;
            } else {
                rs+=k;
            }
        }
        return rs;
    }


}

